from rest_framework import serializers
from django_redis import get_redis_connection

from oauth.models import OAuthQQUser
from users.models import User
from oauth.utils import check_open_id


class OauthQQUserSerializer(serializers.Serializer):
    access_token = serializers.CharField(label='操作凭证')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[3-9]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码')

    def validate(self, attrs):
        #     校验　openid , 解码　
        openid = check_open_id(attrs.get('access_token'))
        if openid is None:
            raise serializers.ValidationError('access_token错误')

        attrs['openid'] = openid
        # 校验短信验证码
        sms_code = attrs.get('sms_code')
        redis_conn = get_redis_connection('code')
        redis_code = redis_conn.get('sms_%s' % attrs["mobile"])
        if redis_code is None:
            raise serializers.ValidationError("验证码已过期")

        if sms_code != redis_code.decode():
            raise serializers.ValidationError('短信验证码错误')
        # 校验用户输入的手机号是否注册过
        mobile = attrs.get('mobile')
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            #     如果没有注册过创建用户
            #  程序出现错误，说明该用户没有绑定过该程序，需要新创建用户
            #  在下方create方法中实现
            pass
        else:
            #     如果注册过判断用户输入的密码是否正确
            #  程序　没有报错　说明已经从用户列表中获取到用户，此时校验密码是否正确
            #  获取用户输入的密码
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
            attrs['user'] = user
        return attrs

    def create(self, validated_data):
        """最终要保存 user 和openid信息"""
        user = validated_data.get('user')
        openid = validated_data.get('openid')
        if user is None:
            #  创建
            user = User.objects.create(
                username=validated_data.get('mobile'),
                mobile=validated_data.get('mobile'),
                password=validated_data.get('password')
            )
            #  对密码进行加密
            user.set_password(validated_data.get('password'))
            user.save()
        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )
        return qquser

